package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.*;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error("数据库异常：", ex);  // 记录完整异常堆栈

        if (ex.getMessage() != null && ex.getMessage().contains("Duplicate entry")) {
            try {
                // 更安全的分割方式，处理类似："Duplicate entry 'xxx' for key 'yyy'"的消息
                String[] parts = ex.getMessage().split(" ");
                if (parts.length >= 2) {
                    String duplicateValue = parts[1];
                    return Result.error(duplicateValue + MessageConstant.ALREADY_EXISTS);
                }
            } catch (Exception e) {
                log.warn("解析Duplicate entry消息失败", e);
            }
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }



}
